window.$config = {
    store: {},
    kcishost: location.hostname == 'h5.yixiaoqun.com'?'http://console.kcis.cn':'http://open.test.kcis.cn',
    user: {},
    redirect: location.href,
    url: 'http://yixiaoqun.com/api.php?s=WXOAuth2/infoScope',
    beforeUrl: [],
    wxOption : '',
    wxImgUrl : '?imageMogr2/auto-orient/crop/300x300/quality/80',
    host: function () {
        var base = '/api.php?s=';
        if(location.hostname == 'h5.yixiaoqun.com'){
            return 'http://m.yixiaoqun.com'+base;
        }else if(location.hostname == 'h5.test.yixiaoqun.com'){
            return 'http://test.yixiaoqun.com'+base;
        }else{
            return base;
        }
    },
    //校验
    rex : {
        //手机号
        mobile : /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/
    },
    getCookie :function (c_name) {
        if (document.cookie.length>0) {
            var c_start=document.cookie.indexOf(c_name + "=")
            if (c_start!=-1)
            {
                c_start=c_start + c_name.length+1
                var c_end=document.cookie.indexOf(";",c_start)
                if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end))
            }
        }
        return ""
    },
    //设置cookie
    setCookie: function (c_name, value, expiredays ) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + value + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())+';path=/';
    },
    GetQueryString:function(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    },
    dataURLtoBlob: function (base64Data) {
        var byteString;
        if (base64Data.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(base64Data.split(',')[1]);
        else
            byteString = unescape(base64Data.split(',')[1]);
        var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ia], {type:mimeString});
    },
    audioAutoPlay: function(){
        var audio = document.getElementById('bgmusic');
        audio.play();
        document.addEventListener("WeixinJSBridgeReady", function () {
            audio.play();
        }, false);
        document.addEventListener('YixinJSBridgeReady', function() {
            audio.play();
        }, false);
    
        $('.music').click(function(){
            if(audio!==null) {
                if(audio.paused){
                    audio.play();
                    $('.music').addClass('on');
                }else{
                    audio.pause();
                    $('.music').removeClass('on');
                }
            }
        });
    },
    // 滚动页面到指定位置
    toScrollElement (ele){
        if(ele){
            setTimeout(()=>{
                var offTop = document.querySelector(ele).offsetTop;
                document.documentElement.scrollTop = document.body.scrollTop = offTop;
            },100)
        }
    },
    IsPC : function () {
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone",
            "SymbianOS", "Windows Phone",
            "iPad", "iPod"];
        var flag = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = false;
                break;
            }
        }
        return flag;
    },
    iswx : function(){
        var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            return true;
        }else{
            return false;
        }
    },
    wxConfig: function (config) {
        wx.config({
            debug: false,
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: [
                'chooseImage', 'uploadImage', 'previewImage' ,'onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo'
            ]
        });

    },
    wxShare : function(Option) {
        if(!this.iswx()) return;
        var num = 0,
            _this = this,
            time = setInterval(function () {
                if(num>100) {
                    clearTimeout(time);
                }
                try {
                    if (!wx || !oe_wxconfig) {};
                } catch (e) {
                    num++;return;
                }

                clearTimeout(time);

                _this.wxConfig(oe_wxconfig);
                //初始化
                if (!Option) Option = {};
                var title = Option.title ? Option.title : "一小群",
                    summary = Option.cont ? Option.cont : "一小群，优质的社群营销工具",
                    link = Option.url ? Option.url : location.href,
                    thumb = Option.logo ? Option.logo : 'http://' + location.hostname + '/logo.jpg',
                    content = {
                        title: title,
                        desc: summary,
                        link: link,
                        imgUrl: thumb,
                        /*type: '',
                        dataUrl: '',*/
                        success: function () {
                            if(Option.success){
                                Option.success();
                            }
                        },
                        cancel: function () {
                        }
                    }
                wx.ready(function () {
                    wx.onMenuShareTimeline(content);
                    wx.onMenuShareAppMessage(content);
                    wx.onMenuShareQQ(content);
                    wx.onMenuShareWeibo(content);
                    // alert(JSON.stringify(content))
                });
            },100);
    },
    // 微信授权
    wxVerify (value){
        if (!this.getCookie('yxq_wx_token') || this.getCookie('yxq_wx_token')=='abc1024' && (location.hostname == 'h5.test.yixiaoqun.com' || location.hostname == 'h5.yixiaoqun.com')) {
            var href = encodeURIComponent(location.href.split('?')[0]+'?aid='+$config.GetQueryString('aid')+(value?value:'')),
                tourl = this.url + '&h52go=' + href;
            location.href = tourl;
            return false;
        }else{
            if(document.body.style.display = 'none'){
                document.body.style.display = 'block';
            }
            return true;
        }
    },
    // 初始化
    init : function () {
        if((location.hostname=='192.168.10.147' || location.hostname=='localhost') && !this.getCookie('yxq_wx_token')){
            this.setCookie('yxq_wx_token','9fb6IKRV8%2BrdJZhKCuRwWNRbT%2BoQ8fHEQ%2FcLQAeb%2BStPF5O1Y6RqeMUFV9wCpc9UDo4dYIwRfymsyCLDeCBxHpX8PpUuuak607xTplpn3nitHENjPQNtCHLk1HApExg4jXzVAoBPrx%2Blsumt')
        }
        if (!this.iswx()) return;
        // var hostname = location.hostname=='h5.yixiaoqun.com'?'test.yixiaoqun.com':'test.yixiaoqun.com';
        var jwx1 = document.createElement('script');
        jwx1.setAttribute('src', 'http://res.wx.qq.com/open/js/jweixin-1.2.0.js');
        document.body.appendChild(jwx1);
        var jwx2 = document.createElement('script');
        jwx2.setAttribute('src', 'http://test.yixiaoqun.com/helper.php?s=WxHelper/config&domain=yixiaoqun.com');
        document.body.appendChild(jwx2);
    }
}

$config.init();

//拓展Vue
if(typeof Vue == 'function'){
    Vue.http.options.emulateJSON = true;
    Vue.http.interceptors.push(function(request, next) {//拦截器
        // 跨域携带cookie
        request.credentials = true;
        next()
    })
    Vue.mixin({
        methods:{
            common (){
                return {
                    httplock : true,
                    // 转化空格
                    converBr(value) {
                        var str = value.replace(/\r\n/g, '<br>');
                        str = str.replace(/[\r,\n]/g, '<br>');
                        return str;
                    },
                    //封装http请求
                    http(_this, config) {
                        //加锁
                        if (config.lock) {
                            if (!this.httplock) return;
                            this.httplock = false;
                        }
                        ;
                        var successCallback = (res) => {
                                var json = res.body;
                                if (json.code == 1 || json.code == 40005 || config.allow) {
                                    if (config.success) config.success.call(_this, json);
                                } else {
                                    swal({
                                        title: json.message,
                                        type: "warning"
                                    })
                                    if (config.error) config.error.call(_this, json);
                                }
                                //关闭loading
                                if (config.loading) {
                                    setTimeout(() => {
                                        _this.load.loading = false;
                                    }, 250)
                                }
                                //后续事件
                                if (config.after) config.after.call(_this, json);
                                //解锁
                                if (config.lock) {
                                    setTimeout(() => {
                                        this.httplock = true;
                                    }, config.locktime ? config.locktime : 0);
                                }
                            },
                            errorCallback = (res) => {
                                // alert(JSON.stringify(res));
                                var json = res.body;
                                swal({
                                    title: '网络故障!',
                                    type: "warning"
                                })
                                //解锁
                                if (config.lock) {
                                    setTimeout(() => {
                                        this.httplock = true;
                                    }, config.locktime ? config.locktime : 0);
                                }
                            }
                        config.type = config.type || 'post';
                        if (config.type == 'post') {
                            var options = config.options ? config.options : null;
                            _this.$http[config.type]($config.host() + config.url, config.body, options).then(successCallback, errorCallback)
                        } else {
                            _this.$http[config.type]($config.host() + config.url, config.body).then(successCallback, errorCallback)
                        }
                    },
                    //分享签名串
                    getShareSign (option){
                        var postData = {
                            sharePlatform : 'webApp',
                            shareItem : option.item,
                            previousSignId : $config.GetQueryString('sharesign') || ''
                        }
                        if(!this.dataPoint.sign){
                            Vue.http.post($config.host()+'ShareLog/getShareSign',postData).then((res)=>{
                                if(res.body.code==1){
                                    let sign = res.body.data.signId;
                                    this.dataPoint.sign = sign;
                                    option.success();
                                }
                            },(res)=>{
                                option.success();
                            })
                        }else{
                            option.success();
                        }

                    },
                    //埋点
                    buryPoint (option,json){
                        let postData = {
                            eventCommonData : {
                                lastUrl : '',
                                platform : 'webApp',
                                eventModule : option.module,     //模块标识: topicDetail, topicList, topicPost, groupSetting
                                eventItemId : option.id,
                                eventScene : $config.GetQueryString('form') || '',
                                eventType : json.type,
                            },
                            eventConditionData : json.data || ''

                        }
                        Vue.http.post($config.host()+'DataPoint/logEvent',postData).then((res)=>{
                            // console.log(res.body);
                        })
                    }
                }
            }
        }
    })
}
